package bomber.view;

import java.awt.GridLayout;
import java.awt.Toolkit;
import java.util.HashMap;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import bomber.action.GameAction;
import bomber.model.GameBox;
import bomber.model.GameButton;
import bomber.model.GameButtonPool;
import bomber.model.GameManager;


public class GamePanel extends JPanel{

	private static final long serialVersionUID = 1L;
	private String appName;
	private int size;

	private GameManager gameManager;
	private GameButtonPool buttonPool;

	public GamePanel(GameManager gameManager, String appName) {
		this.gameManager = gameManager;
		this.appName = appName;
		this.size = this.gameManager.getSize();
		this.buttonPool = new GameButtonPool(this.size);

		this.setLayout(new GridLayout(this.gameManager.getSize(), 1));
		this.initView();
	}

	private void initView() {
		if (this.gameManager.hasError()) {
			for (int i = 0; i < size; i++) {
				GamePanelRow row = new GamePanelRow(this.gameManager.getSize());
				
				for (int j = 0; j < size; j++) {
					GameBox gameBox = this.gameManager.getGameBox(i, j);
					
					if (gameBox.getType() == GameBox.ROCK) {
						GameButton gameButton = this.buttonPool.addButton(GameBox.ROCK, i, j);
						gameButton.initCheck();
						row.add(gameButton);
					}
					else if (gameBox.getType() == GameBox.BOMB) {
						GameButton gameButton = this.buttonPool.addButton(GameBox.BOMB, i, j);
						gameButton.addActionListener(new GameAction("bomb", this, gameButton));
						row.add(gameButton);
					}
					else if (gameBox.getType() == GameBox.NUMB) {
						GameButton gameButton = this.buttonPool.addButton(GameBox.NUMB, i, j);
						gameButton.setTextOn(gameBox.getInfo() + "");
						gameButton.addActionListener(new GameAction("numb", this, gameButton));
						row.add(gameButton);
					}
					if (gameBox.getType() == GameBox.ZERO) {
						GameButton gameButton = this.buttonPool.addButton(GameBox.ZERO, i, j);
						gameButton.addActionListener(new GameAction("zero", this, gameButton));
						row.add(gameButton);
					}
				}
				super.add(row);
			}
		}
		else {
			super.add(new JLabel(this.gameManager.getError()));
		}
	}
	
	public void viewAll() {
		HashMap<String, GameButton> buttonMap = this.buttonPool.getHashMap();
		
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				buttonMap.get(this.buttonPool.getKey(i, j)).initCheck();
			}
		}
	}

	/** method view message box */
	public void messageBox(String text, int typ) {
		try {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(this, text, appName, typ);

		} catch (Exception ex) {
			System.err.println("Message Dialog error!");
			System.err.println("Error message: " + ex.toString());
		}
	}
}
